﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CommonLib.Pattern.FSM;
using System;

public class EnemyFSMStateChase : EnemyFSMStateBase
{
	public EnemyFSMStateChase(RoleCtrl _role, IFSM fsm = null) : base("Chase", _role, fsm)
	{

	}
	protected override void OnEnter()
	{
		base.OnEnter();
		TransitionParam tp = GetTransistionParam(TransitionParamType.Chase);
		vigilance = tp.VigilanceChase;
		MaxChaseTime = tp.ChaseMaxTime;
		startChaseTime = Time.fixedTime;
		//Role = (machine as FSMEnemy).roleCtrl;
	}

	internal bool IsTimeOut()
	{
		return ChaseTime >= MaxChaseTime;
	}

	protected override void OnExit()
	{
		base.OnExit();
		startChaseTime = 0;
		//Role = null;
	}

	protected override void OnUpdate()
	{
		base.OnUpdate();
		Collider2D chaseTarget = target;
		if(FindNearestChase(vigilance, out Collider2D col))
		{
			chaseTarget = col;
		}
		if( null != chaseTarget)
		{
			Vector2 steering = new Vector2(chaseTarget.transform.position.x - Role.transform.position.x,
					chaseTarget.transform.position.y - Role.transform.position.y).normalized;

			Vector2 desired = (Role.SubManagerMove.VelocityDir + steering).normalized;
			//role.SubManagerMove.Rb2d.velocity = desired.normalized * role.RoleEntity.CurrentSpeed;
			Role.SubManagerMove.SetVelocityDir(desired);
			LastTarget = chaseTarget;
		//	Debug.Log("EPChainNodeAttackOther");
		}
		else
		{
			LastTarget = null;
		//	Debug.Log("EPChainNodeAttackOther Not");
		}
		/*
		if (FindOthers(Role, Role.transform.position, new Vector2(10, 10), out Collider2D col))
		{
			Vector2 steering = new Vector2(col.transform.position.x - Role.transform.position.x,
				col.transform.position.y - Role.transform.position.y).normalized;

			Vector2 desired = (Role.SubManagerMove.VelocityDir + steering) / 2;
			//role.SubManagerMove.Rb2d.velocity = desired.normalized * role.RoleEntity.CurrentSpeed;
			Role.SubManagerMove.SetVelocityDir(desired);
			Debug.Log("EPChainNodeAttackOther");
		}
		*/
	}


	public Collider2D LastTarget { get; protected set; }
	protected float startChaseTime = 0;
	protected float ChaseTime => Time.fixedTime - startChaseTime;
	protected float MaxChaseTime { get; set; } = 0;
}
